<?php

namespace api\modules\v1\forms\rbac;

use Yii;
use yii\base\Model;
use common\models\base\Project;
use common\models\member\Attr;
use common\models\rbac\Department;
use common\models\member\Member;

/**
 * 部门
 *
 * Class DepartmentForm
 * @package api\modules\v1\forms\rbac
 */
class DepartmentForm extends Model
{
    /**
     * 部门ID
     *
     * @var
     */
    public $id;

    /**
     * 项目ID
     *
     * @var
     */
    public $project_id;

    /**
     * 父部门ID
     *
     * @var
     */
    public $pid;

    /**
     * 层级
     *
     * @var
     */
    public $level;

    /**
     * 部门名称
     *
     * @var
     */
    public $name;

    /**
     * 部门负责人
     *
     * @var
     */
    public $department_leader;

    /**
     * 部门总人数
     *
     * @var
     */
    public $total_num;

    /**
     * 部门状态
     *
     * @var
     */
    public $status;

    /**
     * 用户UID
     *
     * @var
     */
    public $member_id;

    /**
     * 负责人IDs【','分割】
     *
     * @var
     */
    public $leader_ids;

    /**
     * 部门信息
     *
     * @var array
     */
    protected $department;

    /**
     * 成员列表
     *
     * @var array
     */
    protected $memberList = [];

    /**
     * 成员属性列表
     *
     * @var array
     */
    protected $memberAttrList = [];

    /**
     * 成员属性列表【取消负责人】
     *
     * @var array
     */
    protected $memberAttrCancelList = [];


    public function rules()
    {
        return [

            // 参数验证
            [['member_id', 'project_id', 'name', 'status'], 'required', 'message' => '{attribute}不能为空', 'on' => ['create']],
            [['member_id', 'id', 'project_id', 'name', 'status'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit']],
            [['member_id', 'id', 'project_id', 'status'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit_status']],

            [['member_id'], 'checkMemberId', 'skipOnEmpty' => false, 'on' => ['create', 'edit', 'edit_status']],
            [['id'], 'checkDepartment', 'skipOnEmpty' => false, 'on' => ['edit', 'edit_status']],
            [['project_id'], 'checkProjectId', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['name'], 'checkName', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['leader_ids'], 'checkLeaderIds', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['status'], 'checkStatus', 'skipOnEmpty' => false, 'on' => ['create', 'edit', 'edit_status']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 新增
        $scenarios['create'] = ['member_id', 'project_id', 'name', 'leader_ids', 'status'];

        // 编辑
        $scenarios['edit'] = ['member_id', 'id', 'project_id', 'name', 'leader_ids', 'status'];

        // 切换部门状态
        $scenarios['edit_status'] = ['member_id', 'id', 'project_id', 'status'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'member_id' => '用户ID',
            'id' => '部门ID',
            'project_id' => '项目ID',
            'name' => '部门名称',
            'leader_ids' => '部门负责人',
            'status' => '部门状态',
        ];
    }

    /**
     * 检验用户UID
     *
     * @param $attribute
     * @return bool
     */
    public function checkMemberId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (Yii::$app->user->identity->member->is_super == Member::IS_SUPER_YES) {
            return true;
        }

        $memberAttr = Yii::$app->services->attr->findInfo([
            'member_id' => $this->member_id,
            'project_id' => $this->project_id,
        ]);

        if (!$memberAttr) {
            $this->addError($attribute, '未绑定该项目,无法操作');
        }
    }

    /**
     * 检验部门信息
     *
     * @param $attribute
     * @return bool
     */
    public function checkDepartment($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $department = $this->getDepartment();
        if (!$department) {
            $this->addError($attribute, '参数错误[id_error]');
            return true;
        }

        if ($department->project_id != $this->project_id) {
            $this->addError($attribute, '该部门非当前项目绑定部门');
            return true;
        }
    }

    /**
     * 检验项目ID
     *
     * @param $attribute
     */
    public function checkProjectId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $project = Yii::$app->services->project->findById($this->project_id);
        if (!$project) {
            $this->addError($attribute, '参数错误[project_id_error]');
            return true;
        }

        if ($project->status != Project::STATUS_ENABLE) {
            $this->addError($attribute, '项目未开启，无法操作');
            return true;
        }
    }

    /**
     * 校验部门名称
     *
     * @param $attribute
     */
    public function checkName($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->name);
        if ($len > 10) {
            $this->addError($attribute, '部门名称过长，最多10个字');
            return true;
        }

        // 是否检验
        $isCheck = true;
        if ($this->getScenario() == 'edit') {
            $department = $this->getDepartment();
            // 部门参数未改变【跳过】
            if ($department->name == $this->name) {
                $isCheck = false;
            }
        }

        if ($isCheck) {
            $departmentInfo = Yii::$app->services->department->findInfo([
                'project_id' => $this->project_id,
                'name' => $this->name,
                'status' => [Department::STATUS_DISABLE, Department::STATUS_ENABLE],
            ]);

            if ($departmentInfo) {
                $this->addError($attribute, "部门【{$this->name}】已存在");
                return true;
            }
        }
    }

    /**
     * 校验负责人IDs
     *
     * @param $attribute
     */
    public function checkLeaderIds($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $memberIds = $this->leader_ids ? array_unique(explode(',', $this->leader_ids)) : [];

        // 成员列表
        $this->memberList = $memberList = Yii::$app->services->member->findList([
            'id' => $memberIds,
            'indexBy' => 'id',
        ]);

        // 成员属性
        $this->memberAttrList = $memberAttrList = Yii::$app->services->attr->findList([
            'member_id' => $memberIds,
            'project_id' => $this->project_id,
            'indexBy' => 'member_id',
        ]);

        // 编辑新增人数
        $newNum = 0;

        // 验证参数
        foreach ($memberList as $row) {
            if (!isset($memberAttrList[$row['id']])) {
                $this->addError($attribute, "{$row['realname']}不属于该项目");
                break;
            }

            if ($memberAttrList[$row['id']]['department_id'] > 0
                && (
                    $this->getScenario() == 'create'
                    || ($this->getScenario() == 'edit' && $memberAttrList[$row['id']]['department_id'] != $this->id)
                )
            ) {
                $this->addError($attribute, "{$row['realname']}已绑定部门");
                break;
            }

            if ($row['status'] != Member::STATUS_ENABLE) {
                continue;
            }

            if ($this->getScenario() == 'create') {
                $newNum++;
            } elseif ($this->getScenario() == 'edit' && $memberAttrList[$row['id']]['department_id'] == 0) {
                $newNum++;
            }
        }

        $nameArr = array_column($memberList, 'realname');
        // 部门负责人
        $this->department_leader = implode(',', $nameArr);
        // 部门人数
        if ($this->getScenario() == 'create') {
            $this->total_num = $newNum;
        } else {
            $attrList = Yii::$app->services->member->findListInnerAttr([
                'project_id' => $this->project_id,
                'department_id' => $this->id,
                'status' => Member::STATUS_ENABLE,
            ]);
            $this->total_num = count($attrList) + $newNum;
        }

        // 取消负责人
        $this->memberAttrCancelList = Yii::$app->services->attr->findList([
            'notin_member_id' => $memberIds,
            'project_id' => $this->project_id,
            'department_id' => $this->id,
            'is_department_leader' => Attr::IS_DEPARTMENT_LEADER_YES,
        ]);
    }

    /**
     * 校验部门状态
     *
     * @param $attribute
     */
    public function checkStatus($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (!in_array($this->status, [Department::STATUS_DISABLE, Department::STATUS_ENABLE])) {
            $this->addError($attribute, "参数错误[status_error]");
            return true;
        }
    }

    /**
     * 部门负责人
     *
     * @return string
     */
    public function getDepartmentLeader(): string
    {
        return $this->department_leader ? $this->department_leader : '';
    }

    /**
     * 部门人数
     *
     * @return int
     */
    public function getTotalNum(): int
    {
        return $this->total_num ? $this->total_num : 0;
    }

    /**
     * 会员列表
     *
     * @return array
     */
    public function getMemberList(): array
    {
        return $this->memberList ? $this->memberList : [];
    }

    /**
     * 会员属性列表
     *
     * @return array
     */
    public function getMemberAttrList(): array
    {
        return $this->memberAttrList ? $this->memberAttrList : [];
    }

    /**
     * 会员属性【取消负责人】
     *
     * @return array
     */
    public function getMemberAttrCancelList(): array
    {
        return $this->memberAttrCancelList ? $this->memberAttrCancelList : [];
    }

    /**
     * 获取部门信息
     *
     * @return array|Department|null
     */
    public function getDepartment()
    {
        if (empty($this->department)) {
            $this->department = Yii::$app->services->department->findById($this->id);
        }

        return $this->department;
    }
}
